package classes.multithread;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author : DuJiabao
 * @Date : 2021/1/20 19:10
 * @Project : java_learning
 * @File : null.java
 * @Desc : 生产者与消费者问题
 */
public class PAndC {
    public static void main(String[] args) {
        Clerk clerk = new Clerk();
        Customer customer1 = new Customer(clerk);
        Customer customer2 = new Customer(clerk);
        Producer producer = new Producer(clerk);
        ExecutorService exec = Executors.newCachedThreadPool();
        exec.execute(customer1);
        exec.execute(customer2);
        exec.execute(producer);
        exec.shutdown();
    }
}

class Clerk {
    private int num = 0;

    public Clerk() {
    }

    public Clerk(int num) {
        this.num = num;
    }

    public synchronized void consume() {
        if (num > 0) {
            System.out.println("consume: " + num--);
            notify();
        } else {
            try {
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    public synchronized void produce() {
        if (num < 20) {
            System.out.println("produce: " + num++);
            notify();
        } else {
            try {
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }


}

class Customer implements Runnable {
    private Clerk clerk;

    public Customer() {
    }

    public Customer(Clerk clerk) {
        this.clerk = clerk;
    }

    @Override
    public void run() {
        while (true) {
            clerk.consume();
            try {
                Thread.sleep(200);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

class Producer implements Runnable {
    private Clerk clerk;

    public Producer() {
    }

    public Producer(Clerk clerk) {
        this.clerk = clerk;
    }

    @Override
    public void run() {
        while (true) {
            clerk.produce();
            try {
                Thread.sleep(50);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
